<!--手机壳商品模块-->

<template>
  <div>
    <TableSearch :query="queryParams" :options="searchOpt" :search="handleSearch"/>
    <div class="container">
      <TableCustom :columns="columns" :tableData="tableData" :total="page.total" :viewFunc="handleView"
                   :delFunc="handleDelete" :editFunc="handleEdit" :refresh="refreshPageEvent"
                   :currentPage="page.index"
                   :changePage="changePage"
                   :page-size="page.size"
                   :delSelection="delSelectionGiftEvent"
                   :pageSizeChange="handleSizeChange"
                   @selection-change="selectChanged"
                   :has-pagination="true">
        <template #toolbarBtn>
          <el-button type="warning" :icon="CirclePlusFilled" @click="visible = true">新增</el-button>
          <el-button type="success" :icon="CirclePlusFilled" @click="exportData">导出</el-button>
        </template>
        <template #money="{ rows }">
          ￥{{ rows.money }}
        </template>
        <template #thumb="{ rows }">
          <el-image class="table-td-thumb" :src="rows.thumb" :z-index="10" :preview-src-list="[rows.thumb]"
                    preview-teleported>
          </el-image>
        </template>
        <template #state="{ rows }">
          <el-tag :type="rows.state ? 'success' : 'danger'">
            {{ rows.state ? '正常' : '异常' }}
          </el-tag>
        </template>

        <template #operator="{ rows, index }">
          <template v-if="!rows.editing">
            <el-space>

              <el-switch v-model="rows.giftStatus" active-value="启用" inactive-value="禁用"
                         title="切换状态"
                         @change="updateStatusEvent(rows)">
                <template #active-action>
                  <span class="custom-active-action">E</span>
                </template>
                <template #inactive-action>
                  <span class="custom-inactive-action">T</span>
                </template>
              </el-switch>
              <el-button type="primary" size="small" :disabled="rows.status==0" :icon="CirclePlus"
                         @click="generaCdk(rows)"
                         title="生成CDK">
              </el-button>
              <el-button type="success" size="small" :disabled="rows.status==0" :icon="Edit" @click="handleEdit(rows)"
                         title="编辑">
              </el-button>
              <el-popconfirm
                  confirm-button-text="Yes"
                  cancel-button-text="No"
                  :icon="InfoFilled"
                  icon-color="#626AEF"
                  title="确定删除这条数据吗"
                  @confirm="confirmDeleteEvent(rows)"
              >
                <template #reference>
                  <el-button type="danger" size="small" :icon="Delete" title="删除">

                  </el-button>
                </template>

              </el-popconfirm>
            </el-space>
          </template>
          <template v-else>
            <el-button type="success" size="small" :icon="Select" @click="rows.editing = false">
              保存
            </el-button>
            <!--            <el-button type="default" size="small" :icon="CloseBold" @click="handleCancel(rows, index)">-->
            <!--              取消-->
            <!--            </el-button>-->
          </template>
        </template>

      </TableCustom>

    </div>

    <el-dialog :title="isEdit ? '编辑' : '新增'" v-model="visible" width="700px" destroy-on-close
               :close-on-click-modal="false" @close="closeDialog">
      <TableEdit :form-data="rowData" :options="options" :edit="isEdit" :update="updateData" :cancel="cancelOperation">
        <template #thumb="{ rows }">
          <img class="table-td-thumb" :src="rows.thumb"></img>
        </template>
      </TableEdit>
    </el-dialog>
    <el-dialog title="查看详情" v-model="visible1" width="700px" destroy-on-close>
      <TableDetail :data="viewData">
        <template #thumb="{ rows }">
          <el-image :src="rows.thumb"></el-image>
        </template>
      </TableDetail>
    </el-dialog>

    <el-dialog title="CDK管理" v-model="cdkVisible" destroy-on-close width="900px">
      <cdk-model :giftData="rowData" :cancel="closeCdkPop">

      </cdk-model>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="floorMatManage">
import {getCurrentInstance, onMounted, reactive, ref} from 'vue';
import {ElMessage, ElMessageBox,} from 'element-plus';
import {CirclePlus, CirclePlusFilled, CloseBold, Delete, Edit, InfoFilled, Select} from '@element-plus/icons-vue';
import TableCustom from '@/components/table-custom.vue';
import TableDetail from '@/components/table-detail.vue';
import TableSearch from '@/components/table-search.vue';
import {FormOption, FormOptionList} from '@/types/form-option';
import {GiftManageItem} from "@/types/giftManageItem";
import CdkModel from "@/views/cdkMdel/cdkModel.vue";
import {exportToXlsx} from "@/utils/exportUtils";

const api = getCurrentInstance()?.appContext.config.globalProperties.$api;

// 查询相关
const queryParams = reactive({
  gameName: null,
  appId: null,
  subAppId: null,
  pageSize: 10,
  currentPage: 1,
  gameId: null

});

const page = reactive({
  index: 1,// currentPage
  size: 10, // pageSize
  total: 200, //totalCount
})

const cdkFormData = ref([])

const tableData = ref<GiftManageItem[]>([]);
const cdkVisible = ref(false)
const searchOpt = ref<FormOptionList[]>([
  {type: 'input', label: '礼物ID：', prop: 'giftId'},
  {type: 'input', label: '礼物名称：', prop: 'giftName'},
])
const handleSearch = () => {
  changePage(1);
};

// 表格相关
let columns = ref([
  {type: 'selection'},
  {type: 'index', label: '序号', width: 55, align: 'center'},
  {prop: 'id', label: 'Id', visible: false},
  {prop: 'giftId', label: '礼物ID'},
  {prop: 'giftName', label: '礼物名称'},
  {prop: 'cdkCount', label: 'CDK数量'},
  {prop: 'giftDesc', label: '礼物描述'},
  {prop: 'giftStatus', label: '状态'},
  {prop: 'status', label: '状态', visible: false},
  {prop: 'operator', label: '操作', width: 180},
])

const exportColumn = ref([
  {prop: 'giftId', label: '礼物ID'},
  {prop: 'giftName', label: '礼物名称'},
  {prop: 'cdk', label: 'CDK'},
  {prop: 'batchId', label: '批次ID'},
  {prop: 'giftInsertTime', label: 'CDK生成时间'},
  {prop: 'giftStatus', label: '礼物状态'},
])


const selectRowData = ref([])

const selectChanged = (rows) => {
  selectRowData.value = rows
}

const exportData = async () => {
  let data = selectRowData.value
  if (data.length == 0) {
    data = tableData.value
  }
  let giftIds = []

  data.forEach(item => {
    giftIds.push(item.id)
  })

  if (giftIds.length == 0) {
    ElMessage.info("没有数据可导出")
    return
  }

  let res = await api.post("/api/gift/exportGift", giftIds)
  if (res && res.data) {
    console.log(res.data)
    exportToXlsx(res.data, exportColumn.value, "礼物CDK导出")
  }
}

const updateStatusEvent = (row) => {
  console.log(row)
  let params = {
    "id": row.id,
    status: row.giftStatus == '启用' ? 1 : 0
  }
  api.post("/api/gift/updateStatus", params, (res => {
    if (res.code == 1) {
      ElMessage.success("更新成功")
      row.status = params.status;
    } else {
      ElMessage.error("更新失败")
      row.giftStatus = params.status == 1 ? '禁用' : '启用'
    }
  }))
}

const getGiftShopDataList = async (isFresh = false) => {
  api.post("/api/gift/findList", isFresh ? {} : queryParams, (res) => {
    tableData.value = res.data;
    page.total = res.totalPage;
  })
};

/**
 * 页面加载的时候加载数据
 *
 * */
onMounted(() => {
  getGiftShopDataList();
})

const closeCdkPop = () => {
  cdkVisible.value = false
}
const confirmDeleteEvent = (row) => {
  deleteGifts([{id: row.id}])
}
/**
 * 页码改变事件
 * */
const changePage = (val: number) => {
  page.index = val;
  queryParams.currentPage = page.index;
  queryParams.pageSize = page.size;
  getGiftShopDataList();
};

/**
 * 页数大小改变事件
 * */
const handleSizeChange = (val: number) => {
  page.index = 1;
  page.size = val;
  queryParams.currentPage = page.index;
  queryParams.pageSize = page.size;
};

const delSelectionGiftEvent = (val: GiftManageItem[]) => {
  ElMessageBox.confirm(
      '确定删除这些记录吗',
      'Warning',
      {
        confirmButtonText: 'OK',
        cancelButtonText: 'Cancel',
        type: 'warning',
      }
  )
      .then(() => {
        deleteGifts(val.map(e => ({id: e.id})))
      })
      .catch(() => {

      })
}

/**
 * 刷新按钮事件
 *
 * */
const refreshPageEvent = () => {

  getGiftShopDataList(true);
}

// 新增/编辑弹窗相关
let options = ref<FormOption>({
  labelWidth: '100px',
  span: 24,
  list: [
    {type: 'input', label: '礼物 ID', prop: 'giftId', required: true, placeholder: '请务必填对'},
    {type: 'input', label: '礼物名称', prop: 'giftName', required: true},
    // {type: 'input', label: 'App ID', prop: 'gameAppId', required: true},
    // {type: 'input', label: 'Sub App ID', prop: 'gameSubAppId', required: true},
    // {type: 'input', label: '区域', prop: 'gameArea', required: true},
    {type: 'input', label: '礼物描述', prop: 'giftDesc', required: false},
    // {type: 'number', label: '价格', prop: 'gamePrice', required: true},
    {
      type: 'switch', activeText: 'Yes', inactiveText: 'No', label: ' Bundle', activeValue: 1,

      inactiveValue: 0, prop: "isBundle", required: false
    },
    {
      type: 'switch', activeText: '启用', inactiveText: '禁用', label: '商品状态', activeValue: 1,
      inactiveValue: 0, prop: "status", required: false
    },
    // { type: 'upload', label: '头像', prop: 'thumb', required: true },
  ]
})
const visible = ref(false);
const isEdit = ref(false);
const rowData = ref({});
const editData = ref(false)
const generaCdk = (row: GiftManageItem) => {
  rowData.value = {...row};
  cdkVisible.value = true
  // isEdit.value = true;
  // visible.value = true;
};


const handleEdit = (row: GiftManageItem) => {
  rowData.value = {...row};
  visible.value = true;
  isEdit.value = true;
  editData.value = true;
};

/**
 * 处理点击删除操作事件
 * */
const handleDeleteGift = async (row: GiftManageItem) => {
  let data = {
    id: row.id
  }
  deleteGifts([data]);
}

/**
 *
 * 批量删除操作
 * */
const deleteGifts = async (ids) => {

  api.post("/api/gift/deleteGifts", ids, (res => {
    getGiftShopDataList();
  }))
}

/***
 * 新增/编辑操作
 */
const updateData = async (value) => {
  closeDialog();
  console.log(editData.value)
  if (editData.value == true) {
    editData.value = false
    let res = await api.post("/api/gift/update", value);
    if (res.code == 1) {
      ElMessage.success("更新成功")
    } else {
      ElMessage.error("更新失败")
    }
    getGiftShopDataList();
    return
  }
  await addGiftGoods([value]);
  getGiftShopDataList();
};
/**
 *
 * 取消操作
 * **/
const cancelOperation = () => {
  closeDialog();
}

const closeDialog = () => {
  visible.value = false;
  isEdit.value = false;
};

// 查看详情弹窗相关
const visible1 = ref(false);
const viewData = ref({
  row: {},
  list: []
});
const handleView = (row: GiftManageItem) => {
  viewData.value.row = {...row}
  viewData.value.list = [
    {
      prop: 'id',
      label: '用户ID',
    },
    {
      prop: 'gameID',
      label: '游戏ID',
    },
    {
      prop: 'gameAppId',
      label: 'appId',
    },
    {
      prop: 'gameSubAppId',
      label: 'SubAppId',
    }, {
      prop: 'gameArea',
      label: '商店区',
    },
    {
      prop: 'gameDesc',
      label: '游戏描述',
    }, {
      prop: 'gameStatus',
      label: '状态',
    },
    {
      prop: 'gamePrice',
      label: '价格',
    },
  ]
  visible1.value = true;
};

// 删除相关
const handleDelete = (row: GiftManageItem) => {
  ElMessage.success('删除成功');
  console.log(row)
}

/**
 * 上传商品
 *
 * **/

const addGiftGoods = async (valueArray: any) => {

  await api.post('/api/gift/addGifts', valueArray);

}


</script>

<style scoped>
.table-td-thumb {
  display: block;
  margin: auto;
  width: 40px;
  height: 40px;
}
</style>
